package org.example.controller;


import org.example.model.Article;
import org.example.model.User;
import org.example.service.ArticleService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.web.bind.annotation.PathVariable;
import org.springframework.web.bind.annotation.RequestMapping;
import org.springframework.web.bind.annotation.RestController;
import org.springframework.web.bind.annotation.SessionAttribute;

import java.util.Date;
import java.util.HashMap;
import java.util.List;
import java.util.Map;

@RestController
@RequestMapping("/article")
public class ArticleController {

    //然后注入对象
    @Autowired
    private ArticleService articleService;

    //查询当前用户的文章
    @RequestMapping("/list")
    public Object list(@SessionAttribute("user")User user){
        Article a = new Article();
        a.setId(user.getId());
        List<Article> articles = articleService.list(a);
        Map<String,Object> map = new HashMap<>();
        map.put("nickname",user.getNickname());
        map.put("articles",articles);
        return map;
    }

    @RequestMapping("/select/{id}")
    public Object selectById(@PathVariable Integer id,
                             @SessionAttribute("user")User user){
        Article a = articleService.selectById(id);
        Map<String,Object> map = new HashMap<>();
        map.put("nickname",user.getNickname());
        map.put("articles",a);
        return map;
    }

    @RequestMapping("/add")
    public Object add(Article a,
                      @SessionAttribute("user")User user){
        //补充要插入的字段
        a.setCreateTime(new Date());
        a.setUserId(user.getId());
        int n = articleService.insert(a);
        return a.getId();
    }
}
